<template>
	<view class="warpper">
		<u-navbar :title="$t('order.Initiate-Consignment')" bgColor="#ffffff" @leftClick="goback"
			titleStyle="font-size: 32rpx;font-weight: 500;color: #000000;" placeholder>
		</u-navbar>

		<view class="content">
			<view class="line-cell line-cell-big">
				<view class="line-cell-big__left">
					<view class="line-cell-big__left__top">
						{{ $t('order.Sell-Currency') }}
					</view>
					<view class="line-cell-big__left__bottom" @click="selectCurrency('sell')" :class="{ disabled: isEdit }">
						<view :class="{ 'thin-text': !sellCurrencyLabel }">{{ sellCurrencyLabel || '请选择' }}</view>
						<view class="iconfont icon-xiala"></view>
					</view>
				</view>

				<view class="line-cell-big__center">
					<view class="iconfont icon-duihuan"> </view>
				</view>

				<view class="line-cell-big__right">
					<view class="line-cell-big__left__top">
						{{ $t('order.Receive-Currency') }}
					</view>
					<view class="line-cell-big__left__bottom" :class="{ disabled: isEdit }" @click="selectCurrency('receive')">
						<view :class="{ 'thin-text': !receiveCurrencyLabel }">{{ receiveCurrencyLabel || '请选择' }}</view>
						<view class="iconfont icon-xiala"></view>
					</view>
				</view>
			</view>

			<view class="line-cell">
				<view class="line-cell__left">
					{{ $t('order.Sales-Quantity') }}
				</view>
				<view class="line-cell__right" :class="{ disabled: isEdit }">
					<u--input type="digit" :placeholder="$t('order.Please-Enter')" border="none"
						v-model="releaseTradeForm.totalStock" inputAlign="right" @blur="handleBlur">
					</u--input>
					<view class="line-cell__right__text">
						{{ sellCurrencyLabel }}
					</view>
				</view>
			</view>
			<view class="tip" v-if="currentRate">{{$t('order.Currentrate')}}{{currentRate}}</view>
			<view class="line-cell">

				<view class="line-cell__left">
					{{ $t('order.Exchange-rate') }}
				</view>
				<view class="line-cell__right">
					<u--input type="digit" :placeholder="$t('order.Please-Enter')" border="none"
						v-model="releaseTradeForm.exchangeDetailList[0].targetPrice" inputAlign="right" @blur="handleBlurRate">
					</u--input>
				</view>
			</view>

			<view class="line-cell">
				<view class="line-cell__left">
					{{ $t('order.You-Will-Get') }}
				</view>
				<view class="line-cell__right">

					<view class="deep-text">
						{{ amountAvailable }}
					</view>

					<view class="line-cell__right__text">
						{{ receiveCurrencyLabel }}
					</view>
				</view>
			</view>
		</view>

		<view class="bottom-box">
			<view class="bottom-box__tips">
				<view class="">
					{{ $t('order.Exchange-tips1') }}
				</view>
				<view class="">
					{{ $t('order.Exchange-tips2') }}
				</view>

			</view>
			<u-button class="bottom-box__btn" @click="nextHandle" :loading="isLoading" :loadingText="$t('order.Sell')">
				{{ $t('order.Sell') }}
			</u-button>
		</view>

		<SelectPopup :show.sync="SelectPopupShow" :option="currencyOption" :title="$t('order.currency')" :value="currentCurrency == 'sell' ? releaseTradeForm.sourceCurrency : releaseTradeForm.exchangeDetailList[0]
			.targetCurrencyId" @finish="onChangeCurrency" v-if="SelectPopupShow" labelSigned="currency" valueSigned="id">
		</SelectPopup>
	</view>
</template>

<script>
	import {
		releaseTradeOrder,
		getCurrencyList,
		editTradeOrder,
		setShelfStatus,
		getExchangeRate
	} from '@/services/bourse.js'
	import {
		mapState
	} from "vuex";
	import SelectPopup from '@/components/SelectPopup.vue'
	import {
		getWalletList
	} from '@/services/user.js'
	export default {
		data() {
			return {
				receiptAccountValue: '',
				SelectPopupShow: false,
				currencyValue: 'RUB',
				sellId: 1,
				walletList: [],
				currencyOption: [],
				releaseTradeForm: {
					"tradeScene": 2,
					"tradeType": 0,
					"tradeDescription": "场内交易",
					"sourceCurrency": 1,
					"totalStock": '',
					"tradeAddressId": '',
					"shelfStatus": 1, //	上架状态
					"recipientCountry": "",
					"exchangeDetailList": [{
						"targetCurrencyId": 4,
						"targetPrice": ''
					}]
				},
				isEdit: 0,
				currentCurrency: 'sell', // receive,
				isLoading: false,
				exchangeRate: []
			}
		},
		computed: {
			...mapState(['currentOrderInfo']),
			sellCurrencyLabel() {
				const arr = this.currencyOption?.filter(t => t.id == this.releaseTradeForm.sourceCurrency)
				if (arr.length > 0) {
					return arr[0].currency
				} else {
					return ''
				}
			},
			receiveCurrencyLabel() {
				const arr = this.currencyOption?.filter(t => t.id == this.releaseTradeForm.exchangeDetailList[0]
					.targetCurrencyId)
				if (arr.length > 0) {
					return arr[0].currency
				} else {
					return ''
				}
			},
			amountAvailable() {
				return (this.releaseTradeForm.exchangeDetailList[0].targetPrice * this.releaseTradeForm.totalStock).toFixed(4)
			},
			currentRate() {
				if (this.releaseTradeForm.exchangeDetailList[0].targetCurrencyId && this.releaseTradeForm.sourceCurrency && this
					.exchangeRate && this.exchangeRate.length > 0) {
					try {
						const item = this.exchangeRate.find(t => {
							return t.sourceCurrencyId == this.releaseTradeForm.sourceCurrency && t.toCurrencyId == this
								.releaseTradeForm.exchangeDetailList[0].targetCurrencyId
						})
						return `1 ${item.sourceCurrency} : ${item.exchangeRate} ${item.toCurrency}`
					} catch (error) {
						console.log(error)
						return null
					}
				} else {
					return null
				}
			}
		},
		components: {
			SelectPopup
		},
		onLoad(option) {
			if (option.isEdit) {
				this.isEdit = option.isEdit
				this.editHandle()
			}
			// this._getCurrencyList()
			this.getWalletListData();
			this._getExchangeRate()
			// this.releaseTradeForm.sourceCurrency=this.currencyOption[0].currencyVo.id,
			// this.releaseTradeForm.exchangeDetailList[0] = this.currencyOption[1].currencyVo.id
		},
		// 监听页面返回
		onBackPress(options) {
			if (options.from === 'navigateBack') {
				return false;
			}
			this.goBack();
			return true;
		},
		methods: {
			// 获取国际汇率
			async _getExchangeRate() {
				const {
					success,
					result
				} = await getExchangeRate()
				if (success) {
					this.exchangeRate = result.data
				}
			},
			goback() {
				if (this.isEdit) {
					this._setShelfStatus()
				}
				// uni.navigateBack()
				uni.redirectTo({
					url: '/pagesUser/bourse/release'
				})
			},
			async getWalletListData() {
				var {
					result
				} = await getWalletList();
				this.walletList = result.rows;
				this.currencyOption = [...result.rows].filter(i => {
					return i.currencyVo.isOpen == 1 && i.currencyVo.tradeOpen == 1
				})
				this.currencyOption = this.currencyOption.map((it) => {
					return {
						...it,
						currency: it.currencyVo.currency,
						id: it.currencyVo.id,
					}
				})
				this.releaseTradeForm.sourceCurrency = this.currencyOption[0]?.id
				// this.releaseTradeForm.exchangeDetailList[0] = this.currencyOption[1].id

			},
			// 返回要重新上架
			async _setShelfStatus() {
				const {
					success
				} = await setShelfStatus({
					"tradeId": this.currentOrderInfo.tradeId,
					"shelfStatus": 1
				})
			},
			// 若为编辑,则回调表单
			async editHandle() {
				this.releaseTradeForm = {
					"tradeId": this.currentOrderInfo.tradeId,
					"tradeScene": this.currentOrderInfo.tradeScene,
					"tradeType": this.currentOrderInfo.tradeType,
					"tradeDescription": this.currentOrderInfo.tradeDescription,
					"sourceCurrency": this.currentOrderInfo.sourceCurrency,
					"totalStock": this.currentOrderInfo.totalStock,
					"tradeAddressId": this.currentOrderInfo.tradeAddressId,
					"shelfStatus": this.currentOrderInfo.shelfStatus, //	上架状态
					"recipientCountry": this.currentOrderInfo.recipientCountry,
					"exchangeDetailList": [{
						"targetCurrencyId": this.currentOrderInfo.exchangeDetailList[0].targetCurrencyId,
						"targetPrice": this.currentOrderInfo.exchangeDetailList[0].targetPrice,
						"id": this.currentOrderInfo.exchangeDetailList[0].id,
					}]
				}
			},
			// 获取货币类型
			// async _getCurrencyList() {
			// 	const {
			// 		success,
			// 		result
			// 	} = await getCurrencyList()
			// 	if (success) {
			// 		this.currencyOption = result.data
			// 	}
			// },
			// 选择货币回调
			onChangeCurrency(val) {
				if (this.currentCurrency == 'sell') {
					this.releaseTradeForm.sourceCurrency = val
					this.sellId = val;
					if (this.releaseTradeForm.exchangeDetailList[0]
						.targetCurrencyId == val) {
						this.releaseTradeForm.exchangeDetailList[0]
							.targetCurrencyId = ''
					}
				} else if (this.currentCurrency == 'receive') {
					this.releaseTradeForm.exchangeDetailList[0]
						.targetCurrencyId = val
					if (this.releaseTradeForm.sourceCurrency == val) {
						this.releaseTradeForm.sourceCurrency = ''
					}
				}
				console.log(this.releaseTradeForm.sourceCurrency);
			},
			handleBlurRate(val) {
				try {
					// 限制小数点后四位
					if (val.includes('.')) {
						//小数点后的位数
						let numAfterDot = val.toString().split('.')[1].length;
						//小数点前的位数
						let numBeforeDot = val.toString().split('.')[0].length;
						//最大长度等于小数点前的位数+3（小数点加小数点后两位）
						this.maxlength = numBeforeDot + 5;
						//小数点后的位数大于2，截取
						if (numAfterDot > 4) {
							this.releaseTradeForm.exchangeDetailList[0].targetPrice = val.substr(0, numBeforeDot + 5);
						}
					}
					if (parseFloat(val) > 1000000) {
						this.releaseTradeForm.exchangeDetailList[0].targetPrice = ''
					}
				} catch (e) {
					//TODO handle the exception
				}
			},
			handleBlur(val) {
				try {
					// 限制小数点后四位
					if (val.includes('.')) {
						//小数点后的位数
						let numAfterDot = val.toString().split('.')[1].length;
						//小数点前的位数
						let numBeforeDot = val.toString().split('.')[0].length;
						//最大长度等于小数点前的位数+3（小数点加小数点后两位）
						this.maxlength = numBeforeDot + 5;
						//小数点后的位数大于2，截取
						if (numAfterDot > 4) {
							this.releaseTradeForm.totalStock = val.substr(0, numBeforeDot + 5);
						}
					}
				} catch (e) {
					//TODO handle the exception
				}

				console.log('val', val, this.filterList(this.sellId));
				if (val > this.filterList(this.sellId)) {
					this.releaseTradeForm.totalStock = this.filterList(this.sellId);
					return;
				}
			},
			filterList(val) {
				var data = this.walletList.filter((t) => t.currencyVo?.isOpen == 1 && t.currencyId == val)
				return parseFloat(data[0]?.amount)
			},
			selectCurrency(val) {
				this.currentCurrency = val
				this.SelectPopupShow = true
			},
			// 发布场内交易
			async nextHandle() {
				const verifyData = this.verifyForm()
				if (verifyData.success) {
					this.isLoading = true
					if (this.isEdit) {
						const obj = {
							tradeId: this.releaseTradeForm.tradeId,
							shelfStatus: 1,
							exchangeDetailList: [{
								"id": this.releaseTradeForm.exchangeDetailList[0].id,
								"targetPrice": this.releaseTradeForm.exchangeDetailList[0].targetPrice,
							}]
						}
						const {
							success
						} = await editTradeOrder(obj)
						if (success) {
							uni.showToast({
								title: this.$t('order.edited-successfully'),
								duration: 2000,
								icon: 'none'
							});
							uni.navigateBack();
						}
					} else {
						const {
							success
						} = await releaseTradeOrder(this.releaseTradeForm)
						if (success) {
							uni.showToast({
								title: this.$t('order.Published-successfully'),
								duration: 2000,
								icon: 'none'
							});
							uni.navigateBack({
								delta: 2
							});
						}
					}
					this.isLoading = false
				} else {
					uni.showToast({
						title: verifyData.msg,
						duration: 2000,
						icon: 'none'
					});
				}
				console.log(this.releaseTradeForm);
			},
			// 验证表单,通过返回true,不通过返回错误信息
			verifyForm() {
				let res = {
					success: true,
					msg: ''
				}

				if (this.releaseTradeForm.sourceCurrency == '') {
					res.success = false
					res.msg = this.$t('order.verify-tips4')
					return res
				}

				if (this.releaseTradeForm.exchangeDetailList[0]
					.targetCurrencyId == '') {
					res.success = false
					res.msg = this.$t('order.verify-tips5')
					return res
				}

				if (this.releaseTradeForm.totalStock == '' || this.releaseTradeForm.totalStock == 0) {
					res.success = false
					res.msg = this.$t('order.verify-tips1')
					return res
				}
				if (this.releaseTradeForm.exchangeDetailList[0].targetPrice == '' || this.releaseTradeForm
					.exchangeDetailList[0].targetPrice == 0) {
					res.success = false
					res.msg = this.$t('order.verify-tips6')
					return res
				}
				return res
			}
		}
	}
</script>

<style lang="scss" scoped>
	.tip {
		font-size: 24rpx;
		font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;
		font-weight: 400;
		color: #fe6600;
		margin-top: 20rpx;
	}

	.disabled {
		pointer-events: none !important;
		opacity: 0.4;
	}

	.warpper {
		.content {
			margin: 30rpx;
			border-radius: 20rpx;
			overflow: hidden;
			padding: 0 20rpx;
			background: #FFFFFF;

			&>view:last-child {
				box-shadow: none;
			}

			.line-cell {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 112rpx;
				background: #FFFFFF;
				box-shadow: inset 0px -2rpx 0px 0px rgba(0, 0, 0, 0.05);
				font-size: 28rpx;
				font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;
				font-weight: 400;
				color: #000000;

				&__right {
					// max-width: 320rpx;
					display: flex;
					align-items: center;

					&__text {
						margin-left: 10rpx;
					}

					.thin-text {
						color: rgba(0, 0, 0, 0.3)
					}

					.deep-text {
						color: #FE6600;
					}

					&__icon {
						font-size: 30rpx;
						color: rgba(0, 0, 0, 0.2);
					}
				}
			}

			.line-cell-big {
				box-sizing: border-box;
				height: 190rpx;
				align-items: center;
				padding: 36rpx 0;
				font-size: 24rpx;
				color: rgba(0, 0, 0, 0.3);
				line-height: 36rpx;
				align-items: end;

				&__left,
				&__right {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					height: 100%;

					&__top {}

					&__bottom {
						box-sizing: border-box;
						display: flex;
						justify-content: space-between;
						padding: 16rpx 12rpx;
						// width: 281rpx;
						height: 72rpx;
						background: #F6F6F6;
						border-radius: 20rpx;
						font-size: 28rpx;
						color: #000000;

						.icon-xiala {
							font-size: 24rpx;
							color: #BFBFBF;
						}

						.thin-text {
							color: rgba(0, 0, 0, 0.3);
						}
					}
				}

				&__center {
					text-align: center;
					width: 88rpx;
					margin-bottom: 18rpx;

					.icon-duihuan {
						font-size: 42rpx;
						color: #878787;
					}

				}
			}
		}


		.bottom-box {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 750rpx;
			background-color: #FFFFFF;

			&__tips {
				font-size: 28rpx;
				font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;
				font-weight: 400;
				color: rgba(0, 0, 0, 0.3);
				line-height: 40rpx;
				padding: 10rpx 30rpx;
				background-color: #f6f6f6;
			}

			&__btn {
				margin: 10rpx 30rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				width: 690rpx;
				height: 80rpx;
				color: #FFFFFF;
				background: #61BDB2;
				border-radius: 80rpx;
			}
		}
	}
</style>